package com.example.administrator.handler_thread_message;

import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    ProgressBar bar = null;
    Button startButton = null;
    private Handler updateBarHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bar = (ProgressBar) findViewById(R.id.bar);
        startButton = (Button) findViewById(R.id.button);
        startButton.setOnClickListener(new ButtonListener());
    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            bar.setVisibility(View.VISIBLE);

            updateBarHandler.post(updateThread);

        }
    }

        Runnable updateThread = new Runnable() {
            int i = 0;
        @Override
        public void run() {
            System.out.println("Begin Thread");
            i = i+10;
            Message msg = updateBarHandler.obtainMessage();

            msg.arg1 = i;
            try{
                    Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            if(i == 110){
                Log.v("exit",String.valueOf(i));
                updateBarHandler.removeCallbacks(updateThread);
            }
            else{
                updateBarHandler.sendMessage(msg);
            }
        }
    };
}
